import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { formatMessage, FormattedMessage } from 'umi/locale';
import {
  Button,
  Input,
  Table,
  Form,
  Divider,
  Select,
  Row,
  Col,
  Popconfirm,
  Pagination,
} from 'antd';
import styles from './index.less';

const FormItem = Form.Item;
const { Option } = Select;
const { Search } = Input;

@connect(({ devices, loading }) => ({
  devices,
  loading: loading.models.devices,
}))
@Form.create()
class GroupDevice extends PureComponent {
  state = {
    selectedRowKeys: [],
  };

  columns = [
    {
      key: 'name',
      title: formatMessage({ id: 'app.dm.devices.name' }),
      dataIndex: 'name',
    },
    {
      key: 'productName',
      title: formatMessage({ id: 'app.dm.devices.product' }),
      dataIndex: 'productName',
    },
    {
      key: 'type',
      title: formatMessage({ id: 'app.dm.devices.nodeType' }),
      render: (text, record) => {
        if (record.type === 1) {
          return <FormattedMessage id="app.dm.product.info.type.device" />;
        }
        if (record.type === 2) {
          return <FormattedMessage id="app.dm.product.info.type.gateway" />;
        }
        return null;
      },
    },
    {
      key: 'state',
      title: formatMessage({ id: 'app.dm.devices.state' }),
      render: (text, record) => {
        if (record.state === 1) {
          return <FormattedMessage id="app.dm.devices.info.notactive" />;
        }
        if (record.state === 3) {
          return <FormattedMessage id="app.dm.devices.info.disabled" />;
        }
        if (record.state === 4) {
          return <FormattedMessage id="app.dm.devices.info.online" />;
        }
        if (record.state === 5) {
          return <FormattedMessage id="app.dm.devices.info.offline" />;
        }
        return null;
      },
    },
    {
      key: 'lastUpTime',
      title: formatMessage({ id: 'app.dm.devices.lastTime' }),
      dataIndex: 'lastUpTime',
    },
    {
      key: 'action',
      title: formatMessage({ id: 'app.dm.devices.table.action' }),
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleView(record.id)}>
            <FormattedMessage id="app.dm.devices.table.action.view" />
          </a>
          <Divider type="vertical" />
          <Popconfirm
            title={
              <div style={{ width: 280, fontWeight: 'bold', color: '000' }}>
                <span>
                  {formatMessage({ id: 'app.dm.devices.del.confirm' }, { name: record.name })}
                </span>
              </div>
            }
            onConfirm={() => this.handleDelete(record.id)}
          >
            <a>
              <FormattedMessage id="app.dm.devices.table.action.del" />
            </a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'devices/init',
    });
  }

  handleDelete = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'devices/del',
      payload: id,
    });
  };

  handleView = id => {
    router.push(`/dm/devices/detail/${id}`);
  };

  render() {
    const {
      devices: { list, pagination, products },
      loading,
      dispatch,
    } = this.props;

    const { selectedRowKeys } = this.state;

    const {
      form: { getFieldDecorator, getFieldsValue },
    } = this.props;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      onShowSizeChange(curr, size) {
        dispatch({
          type: 'devices/fetch',
          payload: { ...getFieldsValue(), ...{ pageNum: curr, pageSize: size } },
        });
      },
      onChange(curr) {
        dispatch({
          type: 'devices/fetch',
          payload: { ...getFieldsValue(), ...{ pageNum: curr, pageSize: pagination.currentSize } },
        });
      },
    };

    const changeProduct = value => {
      dispatch({
        type: 'devices/fetchAndCount',
        payload: { ...getFieldsValue(), ...{ productId: value } },
      });
    };

    const search = value => {
      dispatch({
        type: 'devices/fetch',
        payload: { ...getFieldsValue(), ...{ name: value } },
      });
    };

    let options = [];

    if (products) {
      options = products.map(d => <Option key={d.id}>{d.name}</Option>);
    }

    const isSelected = selectedRowKeys.length === 0;

    const rowSelection = {
      selectedRowKeys,
      onChange: selectedKeys => {
        this.setState({
          selectedRowKeys: selectedKeys,
        });
      },
    };

    return (
      <Form layout="inline">
        <Row>
          <Col span={8}>
            <span style={{ fontSize: '16px', color: 'rgba(0, 0, 0, 0.85)', fontWeight: 500 }}>
              <FormattedMessage id="app.dm.groups.detail.devicelist" />
            </span>
          </Col>
          <Col span={16} style={{ textAlign: 'right' }}>
            <FormItem>
              <Button style={{ marginLeft: 8 }}>刷新</Button>
            </FormItem>
            <FormItem style={{ marginRight: 0 }}>
              <Button type="primary">添加设备到分组</Button>
            </FormItem>
          </Col>
        </Row>
        <Row>
          <FormItem>
            {getFieldDecorator('productId', {
              initialValue: -1,
            })(
              <Select style={{ width: '200px' }} showSearch onChange={changeProduct}>
                <Option key={-1} value={-1}>
                  <FormattedMessage id="app.dm.devices.product.all" />
                </Option>
                {options}
              </Select>,
            )}
          </FormItem>
          <FormItem>
            {getFieldDecorator('name')(
              <Search
                className={styles.extraContentSearch}
                placeholder={formatMessage({ id: 'app.dm.devices.search' })}
                onSearch={search}
              />,
            )}
          </FormItem>
        </Row>
        <Table
          columns={this.columns}
          rowSelection={rowSelection}
          dataSource={list}
          pagination={false}
          loading={loading}
          rowKey="id"
          style={{ marginTop: 15 }}
        />
        <Row style={{ marginTop: 15 }}>
          <Col span={12} style={{ lineHeight: '40px', height: '40px' }}>
            <FormItem>
              <Button type="primary" disabled={isSelected} style={{ marginLeft: 8 }}>
                从分组中删除
              </Button>
            </FormItem>
          </Col>
          <Col
            span={12}
            style={{ textAlign: 'right', lineHeight: '40px', height: '40px', paddingTop: '4px' }}
          >
            <Pagination {...paginationProps} />
          </Col>
        </Row>
      </Form>
    );
  }
}

export default GroupDevice;
